/**
 * 增强路径匹配功能示例
 * 展示方案2的智能路径匹配能力
 */

// 示例：高级路径模式配置
const ADVANCED_API_PATTERNS = {
  // 1. 基础参数化路径
  'GET /api/v1/users/:id': { controller: 'user', method: 'getDetail' },
  'PUT /api/v1/users/:id': { controller: 'user', method: 'update' },
  
  // 2. 多级参数路径
  'GET /api/v1/users/:userId/habits/:habitId': { controller: 'habits', method: 'getUserHabitDetail' },
  'POST /api/v1/users/:userId/habits/:habitId/records': { controller: 'habits', method: 'createRecord' },
  
  // 3. 参数类型验证（数字ID）
  'GET /api/v1/habits/:id(\\d+)': { controller: 'habits', method: 'getDetailById' },
  'DELETE /api/v1/habits/:id(\\d+)': { controller: 'habits', method: 'deleteById' },
  
  // 4. 通配符路径（单级）
  'GET /api/v1/files/*/download': { controller: 'upload', method: 'downloadAnyFile' },
  'POST /api/v1/webhooks/*/callback': { controller: 'webhook', method: 'handleCallback' },
  
  // 5. 双通配符路径（多级）
  'GET /api/v1/admin/**/logs': { controller: 'admin', method: 'getLogs' },
  'DELETE /api/v1/cache/**/clear': { controller: 'cache', method: 'clearCache' },
  
  // 6. 复杂嵌套路径
  'GET /api/v1/organizations/:orgId/projects/:projectId/tasks/:taskId': {
    controller: 'tasks',
    method: 'getTaskInProject'
  },
  
  // 7. 可选参数路径（通过通配符实现）
  'GET /api/v1/search/*': { controller: 'search', method: 'globalSearch' },
  'GET /api/v1/export/**': { controller: 'export', method: 'exportData' }
}

// 示例：路径匹配测试用例
const PATH_MATCHING_TESTS = [
  {
    pattern: '/api/v1/users/:id',
    testPaths: [
      { path: '/api/v1/users/123', expected: { id: '123' } },
      { path: '/api/v1/users/abc', expected: { id: 'abc' } },
      { path: '/api/v1/users/123/profile', expected: null }
    ]
  },
  {
    pattern: '/api/v1/habits/:id(\\d+)',
    testPaths: [
      { path: '/api/v1/habits/123', expected: { id: '123' } },
      { path: '/api/v1/habits/abc', expected: null }, // 不匹配非数字
      { path: '/api/v1/habits/456', expected: { id: '456' } }
    ]
  },
  {
    pattern: '/api/v1/users/:userId/habits/:habitId',
    testPaths: [
      { 
        path: '/api/v1/users/123/habits/456', 
        expected: { userId: '123', habitId: '456' } 
      },
      { path: '/api/v1/users/123', expected: null },
      { path: '/api/v1/users/123/habits', expected: null }
    ]
  },
  {
    pattern: '/api/v1/files/*/download',
    testPaths: [
      { path: '/api/v1/files/image.jpg/download', expected: { '*': 'image.jpg' } },
      { path: '/api/v1/files/docs/download', expected: { '*': 'docs' } },
      { path: '/api/v1/files/a/b/download', expected: null } // 单通配符不匹配多级
    ]
  },
  {
    pattern: '/api/v1/admin/**/logs',
    testPaths: [
      { path: '/api/v1/admin/system/logs', expected: { '**': 'system' } },
      { path: '/api/v1/admin/user/activity/logs', expected: { '**': 'user/activity' } },
      { path: '/api/v1/admin/logs', expected: { '**': '' } }
    ]
  }
]

/**
 * 路径匹配功能演示
 * @param {Object} requestManager 请求管理器实例
 */
function demonstratePathMatching(requestManager) {
  console.log('=== 增强路径匹配功能演示 ===')
  
  PATH_MATCHING_TESTS.forEach((test, index) => {
    console.log(`\n测试 ${index + 1}: ${test.pattern}`)
    
    test.testPaths.forEach(({ path, expected }) => {
      const result = requestManager.matchPath(test.pattern, path)
      const success = JSON.stringify(result?.params) === JSON.stringify(expected)
      
      console.log(`  ${path} -> ${success ? '✅' : '❌'}`)
      if (!success) {
        console.log(`    期望: ${JSON.stringify(expected)}`)
        console.log(`    实际: ${JSON.stringify(result?.params || null)}`)
      }
    })
  })
}

/**
 * API路径匹配优先级演示
 * @param {Object} requestManager 请求管理器实例
 */
function demonstrateMatchingPriority(requestManager) {
  console.log('\n=== API路径匹配优先级演示 ===')
  
  // 模拟API映射（包含冲突的路径）
  const testMapping = {
    // 精确匹配（最高优先级）
    'GET /api/v1/users/profile': { controller: 'user', method: 'getCurrentProfile' },
    
    // 参数化匹配
    'GET /api/v1/users/:id': { controller: 'user', method: 'getDetail' },
    
    // 通配符匹配（最低优先级）
    'GET /api/v1/users/*': { controller: 'user', method: 'getUserResource' }
  }
  
  const testCases = [
    {
      path: '/api/v1/users/profile',
      expected: 'getCurrentProfile', // 精确匹配
      description: '精确匹配优先'
    },
    {
      path: '/api/v1/users/123',
      expected: 'getDetail', // 参数化匹配
      description: '参数化匹配'
    },
    {
      path: '/api/v1/users/settings',
      expected: 'getDetail', // 参数化匹配（如果没有精确匹配）
      description: '参数化匹配（作为ID处理）'
    }
  ]
  
  testCases.forEach(({ path, expected, description }) => {
    console.log(`\n${description}:`)
    console.log(`  路径: ${path}`)
    console.log(`  期望方法: ${expected}`)
    // 这里需要实际的匹配逻辑来验证
  })
}

/**
 * 性能对比测试
 * @param {Object} requestManager 请求管理器实例
 */
function performanceComparison(requestManager) {
  console.log('\n=== 性能对比测试 ===')
  
  const testPaths = [
    '/api/v1/users/123',
    '/api/v1/habits/456/records',
    '/api/v1/files/image.jpg/download',
    '/api/v1/admin/system/logs',
    '/api/v1/organizations/1/projects/2/tasks/3'
  ]
  
  const iterations = 10000
  
  // 测试新的增强匹配
  console.time('增强路径匹配')
  for (let i = 0; i < iterations; i++) {
    testPaths.forEach(path => {
      requestManager.matchApiPath('GET', path)
    })
  }
  console.timeEnd('增强路径匹配')
  
  console.log(`\n测试完成: ${iterations * testPaths.length} 次匹配操作`)
}

/**
 * 使用示例
 */
function usageExamples() {
  console.log('\n=== 使用示例 ===')
  
  const examples = [
    {
      title: '基础CRUD操作',
      code: `
// 获取用户详情
request.get('/api/v1/users/123')

// 更新习惯
request.put('/api/v1/habits/456', { name: '新习惯名称' })

// 删除任务
request.delete('/api/v1/todos/789')
      `
    },
    {
      title: '嵌套资源操作',
      code: `
// 获取用户的特定习惯
request.get('/api/v1/users/123/habits/456')

// 为用户的习惯创建记录
request.post('/api/v1/users/123/habits/456/records', {
  date: '2024-01-01',
  completed: true
})
      `
    },
    {
      title: '通配符路径',
      code: `
// 下载任意文件
request.get('/api/v1/files/document.pdf/download')

// 全局搜索
request.get('/api/v1/search/habits?q=运动')

// 清除缓存
request.delete('/api/v1/cache/user/123/clear')
      `
    },
    {
      title: '参数类型验证',
      code: `
// 只匹配数字ID的习惯
request.get('/api/v1/habits/123') // ✅ 匹配
request.get('/api/v1/habits/abc') // ❌ 不匹配（如果配置了数字验证）
      `
    }
  ]
  
  examples.forEach(({ title, code }) => {
    console.log(`\n${title}:${code}`)
  })
}

// 导出演示函数
export {
  ADVANCED_API_PATTERNS,
  PATH_MATCHING_TESTS,
  demonstratePathMatching,
  demonstrateMatchingPriority,
  performanceComparison,
  usageExamples
}

// 默认导出
export default {
  patterns: ADVANCED_API_PATTERNS,
  tests: PATH_MATCHING_TESTS,
  demonstrate: demonstratePathMatching,
  priority: demonstrateMatchingPriority,
  performance: performanceComparison,
  examples: usageExamples
}